package com.greatwqs.wmall.user.provider.controller;

import com.greatwqs.wmall.common.module.model.LoginUser;
import com.greatwqs.wmall.common.module.util.JsonUtil;
import com.greatwqs.wmall.user.provider.model.dto.ChangePasswordDto;
import com.greatwqs.wmall.user.provider.model.dto.LoginDto;
import com.greatwqs.wmall.user.provider.model.dto.UserRegisterDto;
import com.greatwqs.wmall.user.provider.model.vo.LoginVo;
import com.greatwqs.wmall.user.provider.model.vo.UserVo;
import com.greatwqs.wmall.user.provider.service.UserLoginService;
import com.greatwqs.wmall.user.provider.service.UserService;

import lombok.extern.slf4j.Slf4j;

import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * user - 请求处理
 *
 * @author wang-qingsong
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/wmall/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 用户登陆
     *
     * @param loginDto
     */
    @PostMapping(value = "/login")
    public LoginVo login(@RequestBody @Validated LoginDto loginDto) {
        log.info("login traceId：{}, loginDto: {}", TraceContext.traceId(), JsonUtil.toJson(loginDto));
        return userLoginService.login(loginDto);
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping(value = "me/info")
    public UserVo getUserInfo(LoginUser loginUser) {
        log.info("getUserInfo traceId：{}, loginUser: {}", TraceContext.traceId(), JsonUtil.toJson(loginUser));
        return userService.getUserVo(loginUser.getUserId());
    }

    /**
     * 新增用户
     *
     * @param dto
     */
    @PostMapping(value = "/register")
    public Long register(@RequestBody @Validated UserRegisterDto dto) {
        log.info("register traceId：{}, dto: {}", TraceContext.traceId(), JsonUtil.toJson(dto));
        return userService.register(dto);
    }

    /**
     * 修改用户密码
     *
     * @param changePasswordDto 修改密码的DTO
     */
    @PostMapping(value = "/password")
    public void changePassword(LoginUser loginUser,
                               @RequestBody @Validated ChangePasswordDto changePasswordDto) {
        log.info("changePassword traceId：{}, dto: {}", TraceContext.traceId(), JsonUtil.toJson(changePasswordDto));
        changePasswordDto.setUserId(loginUser.getUserId());
        userService.changePassword(changePasswordDto);
    }
}